package com.tyrone.algorithm.sort;

public class Shell {
    /**
     * 对数组内的元素进行排序
     * @param a
     */
    public static void sort(Comparable[] a){
        int h =1;
        while(h<a.length/2){
            h=2*h+1 ;
        }
        while(h>=1){
            //排序
            //找到待插入元素
            for (int i = h; i < a.length ; i++) {
                //插入到有序下序列
                for (int j = i; j >=h ; j=j-h) {
                    if (greater(a[j-h],a[j])){
                        exch(a,j-h,j);
                    }else {
                        break;
                    }
                }
            }
            h/=2;
        }
    }

    /**
     * 判断v是否大于w
     * @param v
     * @param w
     * @return
     */
    private static boolean greater(Comparable v,Comparable w){
        return v.compareTo(w)>0;
    }

    /**
     * 交换a数组中，索引i和索引j处的值
     * @param a
     * @param i
     * @param j
     */
    private static void exch(Comparable[] a,int i,int j){
        Comparable t ;
        t=a[i];
        a[i]=a[j];
        a[j]=t;
    }
}
